home *** CD-ROM | disk | FTP | other *** search
/ NetNews Offline 2 / NetNews Offline Volume 2.iso / news / comp / lang / c-part2 / 15432 < prev    next >
Encoding:
Internet Message Format  |  1996-08-05  |  2.0 KB

  1. Path: news.cern.ch!danpop
  2. From: danpop@mail.cern.ch (Dan Pop)
  3. Newsgroups: comp.lang.c
  4. Subject: Re: Memory leakage
  5. Date: 19 Apr 96 00:35:06 GMT
  6. Organization: CERN European Lab for Particle Physics
  7. Message-ID: <danpop.829874106@news.cern.ch>
  8. References: <4l3582$1v@alice.walrus.com>
  9. NNTP-Posting-Host: ues5.cern.ch
  10. Mime-Version: 1.0
  11. Content-Type: text/plain; charset=US-ASCII
  12. Content-Transfer-Encoding: 7bit
  13. X-Newsreader: NN version 6.5.0 #18 (NOV)
  14.  
  15. In <4l3582$1v@alice.walrus.com> warrenj@walrus.com (Warren Johnson) writes:
  16.  
  17. >Suppose I have a function:
  18. >
  19. >int give_number() {
  20. >   ...
  21. >   ...
  22. >   ...
  23. >}
  24. >
  25. >and in main I have a line :
  26. >
  27. >if(x>give_number()) { 
  28. >  ...
  29. >  ... }
  30. >
  31. >Now my question is this:  give_number() returns an integer.  Obviously 
  32. >the compiler must allocate memory for this integer. 
  33.  
  34. It may be obvious to you, but it's not obvious to most compiler 
  35. implementors, who return that integer in a register :-)
  36.  
  37. >However, we are not 
  38. >returning this integer to an integer pointer, therefore this allocated 
  39. >memory is floating about in the void somewhere without something pointing 
  40. >to it.  Is this memory deallocated when the function is finished running 
  41. >it's course or do i have to do this:
  42.  
  43. The rule is actually very simple: you care about the memory you
  44. allocate yourself and let the compiler care about the memory it allocates
  45. itself.  This way, no memory leaks will ever occur.
  46.  
  47. >y = give_number();
  48. >
  49. >if(x>y) { blabalh}
  50. >
  51. >free(y); // or just let y be deallocated when the function is over with
  52.  
  53. This is a gross mistake:
  54.  
  55. 1. y is not a pointer.
  56.  
  57. 2. y has not been initialized with the value returned by one of the three
  58.    dynamic allocation functions.
  59.  
  60. 3. // is a syntax error in C.  No conforming C compiler will accept it. 
  61.  
  62. Because of #1, the compiler will simply reject your code (assuming a
  63. proper prototype for free() is in scope and ignoring the #3 issue).
  64.  
  65. Dan
  66. --
  67. Dan Pop
  68. CERN, CN Division
  69. Email: danpop@mail.cern.ch 
  70. Mail:  CERN - PPE, Bat. 31 R-004, CH-1211 Geneve 23, Switzerland
  71.